<?php

require_once('Net/IPv4.php');

// $ia = new IntranetAddress( '/path/to/network.inc' );
// if ( $ia->is_intranet( $_SERVER['REMOTE_ADDR'] ) ) {
//     show_intranet_content();
// }
// else {
//     show_extranet_content();
// }

class IntranetAddress {

protected $included_intranet_cidr_list = array();
protected $excluded_intranet_cidr_list = array();

function IntranetAddress($filename) {
    require_once($filename);

    if ( isset($included_intranet_cidr_list) ) {
        $this->included_intranet_cidr_list
            = $this->parse_cidr_list($included_intranet_cidr_list);
    }
    else {
        $msg = "'included_intranet_cidr_list' not found in $filename";
        throw new Exception( $msg, 1 );
    }

    if ( isset($excluded_intranet_cidr_list) ) {
        $this->excluded_intranet_cidr_list
            = $this->parse_cidr_list($excluded_intranet_cidr_list);
    }
    else {
        $msg = "'excluded_intranet_cidr_list' not found in $filename";
        throw new Exception( $msg, 2 );
    }
}

protected function parse_cidr_list( $cidr_list ) {
    $parsed_cidr_list = array();

    if ( !is_array($cidr_list) ) {
        $cidr_list = array( $cidr_list );
    }
    foreach ( $cidr_list as $cidr ) {
        $net = Net_IPv4::parseAddress($cidr);
        if ( PEAR::isError($net) ) {
            throw new Exception( "could not parse $cidr", 3 );
        }
        $parsed_cidr_list[] = array(
            ip2long($net->network),
            ip2long($net->netmask),
        );
    }

    return $parsed_cidr_list;
}

public function is_intranet($ip) {

    $ip = gethostbyname($ip);
    $is_intranet = 0;
    foreach ( $this->included_intranet_cidr_list as $cidr ) {
        if ( $this->IP_in_CIDR( $ip, $cidr ) ) {
            $is_intranet = true;
            break;
        }
    }

    if ( !$is_intranet ) {
        return false;
    }

    foreach ( $this->excluded_intranet_cidr_list as $cidr ) {
        if ( $this->IP_in_CIDR( $ip, $cidr ) ) {
            $is_intranet = false;
            break;
        }
    }

    return $is_intranet;
} // end 'public function is_intranet()'

private function IP_in_CIDR( $ip, $cidr ) {
    $network = $cidr[0];
    $netmask = $cidr[1];
    $ip_net  = ip2long($ip) & $netmask;
    return ( $ip_net == $network );
} // end 'private function IP_in_CIDR()'

} // end 'class IntranetAddress'

?>
